package util;


import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 *
 * @author Martin Haulrich
 */
public class IO {

    /**
     * Reads file with POS-tags in SUC-format.
     * Assumes that a "." always marks the end of a sentence.
     * If the last sentece in the file does not end with a "." this is omitted.
     * @param fn
     * @return
     * @throws java.io.IOException
     */
    public static List<List<WordPOS>> readSUC(String fn) throws IOException {

        BufferedReader input = new BufferedReader(new FileReader(fn));

        List<List<WordPOS>> text = new ArrayList<List<WordPOS>>();

        Pattern p = Pattern.compile("\\s+\\((\\S+).*\"(\\S+)\".*");

        List<WordPOS> currentSentence = new ArrayList<WordPOS>();
        String line;
        while ((line = input.readLine()) != null) {
            line = input.readLine();
            Matcher m = p.matcher(line);
            if (m.matches()) {
                WordPOS wp = new WordPOS(m.group(2), m.group(1));
                currentSentence.add(wp);
                if (wp.word.equals(".")) {
                    text.add(currentSentence);
                    currentSentence = new ArrayList<WordPOS>();
                }
            }
        }
        return text;
    }

    public static List<List<String>> WordPOS2Word(List<List<WordPOS>> text) {

        List<List<String>> out = new ArrayList<List<String>>();

        for (List<WordPOS> wpl : text) {
            List<String> words = new ArrayList<String>(wpl.size());
            out.add(words);
            for (WordPOS wp : wpl) {
                words.add(wp.word);
            }
        }
        return out;
    }
}
